/*************************************************************************
    > File Name    : Acceptor.cc
    > Author       : LiuLei
    > Mail         : 2261459486@qq.com 
    > Created Time : 2022年11月25日 星期五 10时47分10秒
 ************************************************************************/

#include "../../include/server/Acceptor.h"
#include <sys/types.h>
#include <sys/socket.h>

Acceptor::Acceptor(const string &ip, unsigned short port)
: _listenSocket()
, _serverAddr(ip, port)
{

}

Acceptor::~Acceptor()
{

}

void Acceptor::ready()
{
    this->setReuseAddr();
    this->setReusePort();
    this->bind();
    this->listen();
}

int Acceptor::accpet()
{
    int connfd = ::accept(this->getSocketFd(), nullptr, nullptr);
    if(-1 == connfd)
    {
        ::perror("accept in Acceptor::accept()");
    }
    return connfd;
}

int Acceptor::getSocketFd() const
{
    return _listenSocket.getFd();
}

void Acceptor::setReuseAddr()
{
    int on = 1;
    int ret = ::setsockopt(this->getSocketFd(), SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
    if(ret)
    {
        ::perror("setsockopt in Acceptor::setReuseAddr()");
    }
}

void Acceptor::setReusePort()
{
    int on = 1;
    int ret = ::setsockopt(this->getSocketFd(), SOL_SOCKET, SO_REUSEPORT, &on, sizeof(on));
    if(ret)
    {
        ::perror("setsockopt in Acceptor::setReusePort()");
    }
}

void Acceptor::bind()
{
    int ret = ::bind(this->getSocketFd(), 
                     reinterpret_cast<const sockaddr *>(_serverAddr.getInternetAddrPtr()),
                     sizeof(struct sockaddr_in));
    if(ret)
    {
        ::perror("bind in Acceptor::bind()");
    }
}

void Acceptor::listen()
{
    int ret = ::listen(this->getSocketFd(), 128);
    if(ret)
    {
        ::perror("listen in Acceptor::listen()");
    }
}
